﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using CRM.DataAccess.Entities;
using CRM.Business.Services;
using CRM.Encryption;
using Telerik.Web.UI;
using System.Data;

namespace Web.Company
{
    public partial class Companies : System.Web.UI.Page
    {
        static USER user;
        static List<ORGANIZATION> orgs;
        static long? assignedtoID = null;
        static ROLE r;
        protected void Page_Load(object sender, EventArgs e)
        {
            if (IsPostBack)
                return;
            assignedtoID = null;
            user = (USER)Session["User"];
            if (user != null)
            {
                DateTime dt = DateTime.Now;
                DateTime dt2 = dt.AddMonths(-3);
                dpDateCreatedFrom.SelectedDate = new DateTime(dt2.Year, dt2.Month, 1);
                dpDateCreatedTo.SelectedDate = DateTime.Now;
                LoadAllUser();
                LoadEmailTemplate();
                r = RoleService.GetRoleByID((long)user.ROLE_ID);
                if ((!(bool)user.IS_ADMIN) && (!(bool)r.IS_MANAGER))
                {
                    divAssignTo.Visible = false;
                    lbtnExportToCSV.Visible = false;
                    assignedtoID = user.ID;
                }
                
                orgs = getDataSource(dpDateCreatedFrom.SelectedDate, dpDateCreatedTo.SelectedDate.Value.AddHours(24), "", "", "", assignedtoID);
                RadGrid1.DataSource = orgs;
                RadGrid1.DataBind();
               
            }
        }
        private void LoadEmailTemplate()
        {
            ddlEmailTemplate.DataSource = EmailTemplateService.GetEmailTemplateByCondition("", "", "");
            ddlEmailTemplate.DataBind();
            ddlEmailTemplate.Items.Insert(0, new RadComboBoxItem("None", "-1"));
        }
        private void LoadAllUser()
        {
            ddlAssignedTo.Items.Clear();
            List<USER> users = UserService.ListAll();
            if (users != null)
            {
                foreach (USER u in users)
                {
                    ddlAssignedTo.Items.Add(new RadComboBoxItem(u.SUR_NAME + " " + u.NAME, u.ID.ToString()));
                }
            }
            ddlAssignedTo.Items.Insert(0, new RadComboBoxItem("Select an option", "-1"));
        }

        private List<ORGANIZATION> getDataSource(DateTime? dateFrom, DateTime? dateTo, string orgname, string conNumber, string primaryemail, long? assignedtoID)
        {
            List<ORGANIZATION> dt = OrganizationService.GetCompanyByCondition(dateFrom, dateTo, assignedtoID, orgname, conNumber, primaryemail);
            if (dt == null)
            {
                dt = new List<ORGANIZATION>();
            }
            return dt;
        }
        protected void sendEmail_Click(object sender, EventArgs e)
        {
            LinkButton lbtnSendEmail = sender as LinkButton;
            EMAIL_TEMPLATE email = new EMAIL_TEMPLATE();
            email.SUBJECT = " ";
            email.MESSAGE = " ";
            EMAIL_TEMPLATE emailTemplate = EmailTemplateService.GetEmailTemplateByID(Convert.ToInt64(ddlEmailTemplate.SelectedValue.ToString()));
            if (emailTemplate != null)
            {
                email = emailTemplate;

            }
            string mailto = lbtnSendEmail.Text;
            string t = "parent.location='mailto:" + mailto + "?Subject=" + email.SUBJECT + "&Body=" + email.MESSAGE.Replace(" ", "%20").Replace("\r\n", "%0A") + "'";
            ScriptManager.RegisterStartupScript(this.Page, this.GetType(), "", t, true);
        }
        protected void RadGrid1_NeedDataSource(object sender, Telerik.Web.UI.GridNeedDataSourceEventArgs e)
        {
            RadGrid1.DataSource = orgs;
        }
        protected void btnSearch_ServerClick(object sender, EventArgs e)
        {
            if (divAssignTo.Visible)
            {
                long? at = Convert.ToInt64(ddlAssignedTo.SelectedValue);
                assignedtoID = at == -1 ? null : at;
            }
            orgs = getDataSource(dpDateCreatedFrom.SelectedDate, dpDateCreatedTo.SelectedDate.Value.AddHours(24), txtCompanyName.Text.Trim(), txtContactNumber.Text.Trim(), txtPrimaryEmail.Text.Trim(), assignedtoID);
            RadGrid1.DataSource = orgs;
            RadGrid1.DataBind();
        }

        private void LoadAllUser(RadComboBox ddlAssignedTo)
        {
            ddlAssignedTo.Items.Clear();
            List<USER> users = UserService.ListAll();
            if (users != null)
            {
                foreach (USER u in users)
                {
                    ddlAssignedTo.Items.Add(new RadComboBoxItem(u.SUR_NAME + " " + u.NAME, u.ID.ToString()));
                }
            }
        }
        protected void btnAddCompany_ServerClick(object sender, EventArgs e)
        {
            Response.Redirect("AddNewCompany.aspx");
        }
        protected void RadGrid1_ItemCreated(object sender, GridItemEventArgs e)
        {
            if (e.Item is GridPagerItem)
            {
                GridPagerItem oGridPagerItem = (GridPagerItem)e.Item;
                RadComboBox oRadComboBox = (RadComboBox)oGridPagerItem.FindControl("PageSizeComboBox");
                oRadComboBox.Width = Unit.Pixel(50);
            }
        }
        protected void RadGrid1_ItemCommand(object source, GridCommandEventArgs e)
        {
            GridDataItem dataItem = e.Item as GridDataItem;
            switch (e.CommandName)
            {
                case "Edit":
                    Response.Redirect("EditCompany.aspx?id=" + dataItem.GetDataKeyValue("ID").ToString());
                    break;
                case "Delete":
                    long orgID = Convert.ToInt64(dataItem.GetDataKeyValue("ID").ToString());
                    orgs.Remove(orgs.Where(x => x.ID == orgID).FirstOrDefault<ORGANIZATION>());
                    int deleteOrg = OrganizationService.DeleteOrganization(orgID);
                    if (deleteOrg == 1)
                        RadAjaxManager.GetCurrent(this).ResponseScripts.Add(@"ShowMessage('" + "Delete company successful !" + "');");
                        //RadAjaxManager1.ResponseScripts.Add(@"showMessage('" + "Successful" + "', '" + "Delete company successful !" + "');");
                        //ScriptManager.RegisterStartupScript(this.Page, this.GetType(), "", "alert('Delete company successful !');", true);
                    else
                        RadAjaxManager.GetCurrent(this).ResponseScripts.Add(@"ShowMessage('" + "Can not delete company !" + "');");
                        //RadAjaxManager1.ResponseScripts.Add(@"showMessage('" + "Error" + "', '" + "Can not delete company !" + "');");
                        //ScriptManager.RegisterStartupScript(this.Page, this.GetType(), "", "alert('Can not delete company !');", true);
                    break;
                default:
                    break;
            }
        }
        protected void RadGrid1_PreRender(object sender, EventArgs e)
        {
            RadGrid1.MasterTableView.GetColumn("ASSIGN_TO").Visible = true;
            if ((!(bool)user.IS_ADMIN) && (!(bool)r.IS_MANAGER))
            {
                RadGrid1.MasterTableView.GetColumn("ASSIGN_TO").Visible = false;
                RadGrid1.MasterTableView.GetColumn("ORGANIZATION_NAME").ItemStyle.Width = Unit.Percentage(17);
                RadGrid1.MasterTableView.GetColumn("ORGANIZATION_NAME").HeaderStyle.Width = Unit.Percentage(17);
                RadGrid1.MasterTableView.GetColumn("COMPANY_WEBSITE").ItemStyle.Width = Unit.Percentage(18);
                RadGrid1.MasterTableView.GetColumn("COMPANY_WEBSITE").HeaderStyle.Width = Unit.Percentage(18);
            }
            else
            {
                GridColumn col = RadGrid1.MasterTableView.GetColumn("ASSIGN_TO");
                if (col != null)
                {
                    foreach (GridDataItem dataItem in RadGrid1.Items)
                    {
                        RadComboBoxItem assignedToItem = ddlAssignedTo.FindItemByValue(dataItem[col].Text);
                        if (assignedToItem != null)
                            dataItem[col].Text = assignedToItem.Text;
                    }
                }
            }
        }
        protected void lbtnExportToCSV_ServerClick(object sender, EventArgs e)
        {
            RadGrid1.ExportSettings.IgnorePaging = true;
            RadGrid1.ExportSettings.OpenInNewWindow = true;
            RadGrid1.ExportSettings.UseItemStyles = true;
            DateTime dt = DateTime.Now;
            RadGrid1.ExportSettings.FileName = "Companies" + dt.Year + dt.Month + dt.Day;
            RadGrid1.MasterTableView.GetColumn("TOOLS").Display = false;
            RadGrid1.MasterTableView.ExportToCSV();
        }

        protected void lbtnImport_ServerClick(object sender, EventArgs e)
        {
            Response.Redirect("ImportFromExcelFile.aspx");
        }
    }
}